package com.ruoyi.web.controller.admin.chat;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.LlmInfoConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DIfyUtils;
import com.ruoyi.common.utils.RestTemplateClient;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.Map;


/**
 * 在dify 上面封装一套java 代码
 */
@RestController
@RequestMapping("/chat")
public class ChatCollection {


    /**
     * 智能对话流式输出
     *
     * @param dataset       传入dify 值
     * @param Authorization dify key
     * @return 流式输出结果
     */
    @PostMapping(produces = "text/event-stream")
    public SseEmitter chat(@RequestBody JSONObject dataset,
                           @RequestHeader(name = "Authorization") String Authorization) {
        return DIfyUtils.runWorkFlowStream(dataset, Authorization);
    }

    /**
     * 停止对话
     *
     * @param taskId        任务id
     * @param user          用户id
     * @param Authorization dify key
     * @return 结果
     */
    @GetMapping("/stopConversation")
    public AjaxResult stopConversation(@RequestParam("taskId") String taskId,
                                       @RequestParam("user") String user,
                                       @RequestHeader(name = "Authorization") String Authorization) {
        String runUrl = LlmInfoConfig.getBaseUrl() + ":81/v1/chat-messages/" + taskId + "/stop";
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + Authorization);
        JSONObject params = new JSONObject();
        params.put("user", user);

        return AjaxResult.success("success", RestTemplateClient.post(runUrl, headerMap, params.toJSONString(), JSONObject.class).getBody());
    }

    /**
     * 获取用户消息列表最大获取一百条
     *
     * @param user          用户
     * @param Authorization token
     * @return 结果
     */
    @GetMapping("/index")
    public AjaxResult getConversations(@RequestParam("user") String user,
                                       @RequestParam("limit") Long limit,
                                       @RequestHeader(name = "Authorization") String Authorization) {
        String runUrl = LlmInfoConfig.getBaseUrl() + ":81/v1/conversations?user={}&limit={}&sort_by=-created_at";
        String formatUrl = StringUtils.format(runUrl, user, limit);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + Authorization);
        ResponseEntity<JSONObject> jsonObjectResponseEntity = RestTemplateClient.get(formatUrl, headerMap, JSONObject.class);
        return AjaxResult.success("success", jsonObjectResponseEntity.getBody());
    }

    /**
     * 获取会话历史消息
     *
     * @param user          用户
     * @param conversionId  会话id
     * @param Authorization token
     * @return 结果
     */
    @GetMapping("/detail")
    public AjaxResult getConversationMessages(@RequestParam("user") String user,
                                              @RequestParam("conversionId") String conversionId,
                                              @RequestHeader(name = "Authorization") String Authorization) {
        String runUrl = LlmInfoConfig.getBaseUrl() + ":81/v1/messages?user={}&conversation_id={}";
        String formatUrl = StringUtils.format(runUrl, user, conversionId);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + Authorization);
        return AjaxResult.success("success", RestTemplateClient.get(formatUrl, headerMap, JSONObject.class).getBody());
    }

    /**
     * 删除会话
     *
     * @param conversationId 会话id
     * @param Authorization  token
     * @return 结果
     */
    @DeleteMapping("/delete/{conversationId}")
    public AjaxResult deleteConversation(@PathVariable(name = "conversationId") String conversationId,
                                         @RequestBody JSONObject jsonObject,
                                         @RequestHeader(name = "Authorization") String Authorization) {
        String runUrl = LlmInfoConfig.getBaseUrl() + ":81/v1/conversations/{}";
        String formatUrl = StringUtils.format(runUrl, conversationId);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + Authorization);

        ResponseEntity<String> delete = RestTemplateClient.delete(formatUrl, jsonObject.toJSONString(), headerMap, String.class);
        HttpStatusCode statusCode = delete.getStatusCode();
        if (statusCode == HttpStatus.NO_CONTENT) {
            return AjaxResult.success("success");
        } else {
            return AjaxResult.error("error");
        }

    }

    /**
     * 修改会话名称
     *
     * @param conversationId path 会话id
     * @param Authorization  token
     * @return 结果
     */
    @PutMapping("/edit/{conversationId}")
    public AjaxResult updateConversationName(@PathVariable(name = "conversationId") String conversationId,
                                             @RequestBody JSONObject jsonObject,
                                             @RequestHeader(name = "Authorization") String Authorization) {
        String runUrl = LlmInfoConfig.getBaseUrl() + ":81/v1/conversations/{}/name";
        String formatUrl = StringUtils.format(runUrl, conversationId);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + Authorization);
        return AjaxResult.success("success", RestTemplateClient.post(formatUrl, headerMap, jsonObject.toJSONString(), JSONObject.class).getBody());
    }

}
